<?php
declare(strict_types=1);

namespace App\Controller\Api\V1\Group;

use App\Controller\Api\V1\CController;
use App\Model\LiveGift;
use App\Model\Players;
use App\Model\PlayersGift;
use App\Model\UsersGift;
use Hyperf\DbConnection\Db;
use App\Service\GiftService;
use App\Service\Group\GroupMemberService;
use App\Service\Group\GroupNoticeService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\JWTAuthMiddleware;
use Psr\Http\Message\ResponseInterface;

/**
 * Class NoticeController
 *
 * @Controller(prefix="/api/v1/group/gift")
 *
 * @package App\Controller\Api\V1\Group
 */
class GiftController extends CController
{
    /**
     * @var GroupMemberService
     */
    private $groupMemberService;

//    public function __construct(GroupMemberService $groupMemberService)
//    {
//        parent::__construct();
//
//        $this->groupMemberService = $groupMemberService;
//    }

    /**
     * 获取所有礼物
     *
     * @RequestMapping(path="list", methods="get")
     */
    public function list2(): ResponseInterface
    {
//        $group_id = (int)$this->request->input('group_id', 0);

//        info('gift');
        $r = LiveGift::where('status', '=', 100)
            ->orderBy('points', 'asc')
            ->get()->toArray();

        foreach ($r as $k => $v) {
            $r[$k]['price'] = round(data_get($v, 'price'));
        }

//        info('gift', [$r]);
        return $this->response->success([
            "rows" => $r,
        ]);
    }

    /**
     * 选手礼物榜单
     * @Middleware(JWTAuthMiddleware::class)
     * @RequestMapping(path="player", methods="get")
     */
    public function players() : ResponseInterface
    {
        $params = $this->request->inputs(['page_size', 'page', 'activity_id', 'package_id', 'username']);
        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 20);
        $name = data_get($params, 'username', '');
        $activityId = data_get($params, 'activity_id', '');
        $idnums = [];
        $guard = \Hyperf\Utils\Context::get('guard', 'token');
        $user = authJwt($guard)->user();
        $user_id  = data_get($user, 'id');
        info('选手礼物榜单',$user_id);
//        if (!empty($name)) {
            $r = Db::table('signups as o')->leftjoin('players_gift as pg', 'pg.player_id', '=', 'players.sign_id')
                ->leftjoin('players', 'o.id', '=', 'players.sign_id')
                ->select('players.sign_id as player_id', 'players.head_img', 'players.name', 'pg.points', 'o.id_num','o.mine_id', 'pg.order')
                ->where('players.name', 'like', "%$name%")
                ->where('players.activity_id', '=', $activityId)
                ->offset($page * $pageSize - $pageSize)
                ->limit($pageSize)
                ->get();
            $mineids = [];
            foreach ($r as $v) {
                $mine_id = data_get($v, 'mine_id', '');
                $mineids[] = $mine_id;
            }

            if ($user_id) {
                $follow_userA = DB::table('user_follow')
                    ->where('user_id',$user_id)
                    ->whereIn('to_user_id',$mineids)
                    ->pluck('user_id', 'to_user_id')
                    ->toArray();

                $to_follow_userA = DB::table('user_follow')
                    ->where('to_user_id',$user_id)
                    ->whereIn('user_id',$mineids)
                    ->pluck('to_user_id', 'user_id')
                    ->toArray();
            }


            foreach ($r as $k => $v) {
                $points = data_get($v, 'points', 0);
                $playerId = data_get($v, 'player_id', 0);
                $order = data_get($v, 'order', 0);
                $mine_id = data_get($v, 'mine_id', '');
                $headImg = data_get($v, 'head_img', 'https://cdn.rockysports.cn/%E5%BE%AE%E6%AD%A5%E8%AE%A1%E6%97%B6.png');
                if (empty($headImg)) {
                    $headImg = 'https://cdn.rockysports.cn/%E5%BE%AE%E6%AD%A5%E8%AE%A1%E6%97%B6.png';
                }
                $idnum = data_get($v, 'id_num', '');

                $follow_status = 1;
                $is_fans = 0;
                // 关注状态
                if ($user_id) {
//                    $follow_user = DB::table('user_follow')
//                        ->where('user_id', $user_id)
//                        ->where('to_user_id', $mine_id)
//                        ->first();
//
//                    $to_follow_user = DB::table('user_follow')
//                        ->where('to_user_id', $user_id)
//                        ->where('user_id', $mine_id)
//                        ->first();
                    $follow_user = data_get($follow_userA, $mine_id, '');
                    if (!empty($follow_user)) {
                        $follow_status = 2;
                    }

                    $to_follow_user = data_get($to_follow_userA, $mine_id, '');
                    if (!empty($to_follow_user)) {
                        $is_fans = 1;
                    }

                    if ($follow_status == 2) {

                        if (!empty($to_follow_user)) {
                            $follow_status = 3;
                        }
                    }
                }

                if (!empty($idnum)) {
                    if (!isset($idnums[$idnum])) {
                        $idnums[$idnum]['points'] = '0';
                        $idnums[$idnum]['player_id'] = $playerId;
                        $idnums[$idnum]['head_img'] = $headImg;
                        $idnums[$idnum]['is_fans'] = $is_fans;
                        $idnums[$idnum]['follow_status'] = $follow_status;
                        $idnums[$idnum]['mine_id'] = $mine_id;
                        if (!isset($idnums[$idnum]['order'])) {
                            $idnums[$idnum]['order'] = $order;
                        }
                        $idnums[$idnum]['name'] = data_get($v, 'name');
                    }
                    $idnums[$idnum]['points'] += $points;
//                    $idnums[$idnum]['points'] = bcadd($points, $idnums[$idnum]['points']);
                } else {
                    $idnums[$k]['points'] = empty($points) ? 0 : $points;
                    $idnums[$k]['player_id'] = $playerId;
                    $idnums[$k]['head_img'] = $headImg;
                    $idnums[$k]['is_fans'] = $is_fans;
                    $idnums[$k]['follow_status'] = $follow_status;
                    $idnums[$k]['order'] = $order;
                    $idnums[$k]['name'] = data_get($v, 'name');
                    $idnums[$k]['mine_id'] = $mine_id;
                }


            }
            $ages = [];
            foreach ($idnums as $user) {
                $ages[] = $user['points'];
            }
            array_multisort($ages, SORT_DESC, $idnums);

            $idnums = array_values($idnums);
//            $order = $pageSize * $page - $pageSize;
//            foreach ($idnums as $k => $v) {
//                $order ++;
//                $idnums[$k]['order'] = $order;
//            }
            return $this->response->success($idnums);
//        } else {
//            $start = $pageSize * $page - $pageSize;
//            $end = bcsub(bcadd((string)$start, (string)$pageSize), '1');
//            $redisKey = 'LIVE_PLAYER_RANK_V2_'.$activityId;
//            $redis = new \Redis();
//            $redis->connect(env('REDIS_HOST', 'localhost'), (int) env('REDIS_PORT', 6379));
//            $redis->auth(env('REDIS_AUTH', null));
//            $data = $redis->lRange($redisKey, $start, (int)$end);
//            $return = [];
//            if ($data) {
//                foreach ($data as $k => $v) {
//                    $j = json_decode($v, true);
//
//
//                    $model = Db::table('signups')
//                        ->where('id', '=', $j['player_id'])
//                        ->select('mine_id')
//                        ->first();
//
//                    $follow_status = 1;
//                    $is_fans = 0;
//                    // 关注状态
//                    if ($user_id) {
//                        $follow_user = DB::table('user_follow')
//                            ->where('user_id', $user_id)
//                            ->where('to_user_id', data_get($model, 'mine_id',''))
//                            ->first();
//
//                        $to_follow_user = DB::table('user_follow')
//                            ->where('to_user_id', $user_id)
//                            ->where('user_id', data_get($model, 'mine_id',''))
//                            ->first();
//                        if (!empty($follow_user)) {
//                            $follow_status = 2;
//                        }
//
//                        if (!empty($to_follow_user)) {
//                            $is_fans = 1;
//                        }
//
//                        if ($follow_status == 2) {
//
//                            if (!empty($to_follow_user)) {
//                                $follow_status = 3;
//                            }
//                        }
//
//                    }
//                    $j['follow_status'] = $follow_status;
//                    $j['is_fans'] = $is_fans;
//                    $j['mine_id'] = data_get($model, 'mine_id','');
//                    $return[] = $j;
//                }
//            } else {
//                GiftService::PlayerGiftRankV2($activityId, $user_id);
//                $data = $redis->lRange($redisKey, $start, (int)$end);
//                info('data', [$data]);
//                $return = [];
//                if ($data) {
//                    foreach ($data as $k => $v) {
//                        $j = json_decode($v, true);
//
//                        $model = Db::table('signups')
//                            ->where('id', '=', $j['player_id'])
//                            ->select('mine_id')
//                            ->first();
//
//                        $follow_status = 1;
//                        $is_fans = 0;
//                        // 关注状态
//                        if ($user_id) {
//                            $follow_user = DB::table('user_follow')
//                                ->where('user_id',$user_id)
//                                ->where('to_user_id', data_get($model, 'mine_id'))
//                                ->first();
//                            if (!empty($follow_user)) {
//                                $follow_status = 2;
//                            }
//
//                            $to_follow_user = DB::table('user_follow')
//                                ->where('to_user_id', $user_id)
//                                ->where('user_id', data_get($model, 'mine_id'))
//                                ->first();
//
//                            if (!empty($to_follow_user)) {
//                                $is_fans = 1;
//                            }
//
//                            if ($follow_status == 2) {
//
//                                if (!empty($to_follow_user)) {
//                                    $follow_status = 3;
//                                }
//                            }
//
//                        }
//                        $j['follow_status'] = $follow_status;
//                        $j['is_fans'] = $is_fans;
//                        $j['mine_id'] = data_get($model, 'mine_id','');
//
//                        $return[] = $j;
//                    }
//                }
//            }
//
//            return $this->response->success($return);
//        }

        $page = data_get($params, 'page', 20);
        $pageSize = data_get($params, 'page_size', 1);
        $activityId = (int)$this->request->input('activity_id', 0);
        $model = Players::where('players.activity_id', '=', $activityId)
            ->leftjoin('players_gift as pg', 'pg.player_id', '=', 'players.sign_id')
            ->leftjoin('signups as o', 'o.id', '=', 'players.sign_id');

//        $model = PlayersGift::where('players_gift.activity_id', '=', $activityId)
//            ->join('players as p', 'p.sign_id', 'players_gift.player_id');
//            ->leftjoin('user_detail as u', 'u.user_id', '=', 'p.user_id');

        $count = $model->count();

        $rows  = [];
        $idnums = [];
        if ($count > 0) {
            $model->orderBy('pg.points', 'desc');

            $rows = $model->forPage($page, $pageSize)->get(['players.id as player_id', 'players.head_img', 'players.name', 'pg.points','o.mine_id', 'o.id_num'])->toArray();


            foreach ($rows as $k => $v) {
                if (!data_get($v, 'points')) {
                    $rows[$k]['points'] = 0;
                }

                $idnum = data_get($v, 'id_num', '');
                if (!empty($idnum)) {

                }
                $img = data_get($v, 'head_img', '');
                if (empty($img)) {
                    $rows[$k]['head_img'] = 'https://cdn.rockysports.cn/%E5%BE%AE%E6%AD%A5%E8%AE%A1%E6%97%B6.png';
                }
            }
        }

        return $this->response->success($rows);
    }

    /**
     * 用户发礼物榜单
     *
     * @RequestMapping(path="user", methods="get")
     */
    public function users() : ResponseInterface
    {
        $params = $this->request->inputs(['page_size', 'page', 'package_id']);

        $page = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 20);
        $activityId = (int)$this->request->input('activity_id', 0);
        $model = UsersGift::where('users_gift.activity_id', '=', $activityId)
            ->join('users_live as u', 'u.user_id', '=', 'users_gift.user_id');

        $count = $model->count();

        $rows  = [];
        if ($count > 0) {
            $model->orderBy('users_gift.points', 'desc');

            $rows = $model->forPage($page, $pageSize)->get(['u.user_id', 'u.nickname', 'u.head_img', 'users_gift.points'])->toArray();
        }

        return $this->response->success($rows);
    }





}
